#pragma once
#include <iostream>
#include <cstring>
#include <sys/types.h> 
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "Log.hpp"
#include "Error.hpp"

const int defaultFd = -1;
const int backlog = 25;

class Sock
{
public:
    Sock(int fd = defaultFd) : _sock(fd)
    {
    }

    void Socket()  // server/client
    {

        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            logMessage(Fatal, "socket failed...");
            exit(SOCKET_ERR);
        }
        logMessage(Debug,"Socket susscess...");
    }

    void Bind(uint16_t& serverport) // server
    {

        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        server.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(server);
        int n = bind(_sock, (struct sockaddr *)&server, len);
        if (n < 0)
        {
            logMessage(Fatal, "bind failed...");
            exit(BIND_ERR);
        }
        logMessage(Debug,"Bind susscess...");

    }

    void Listen() // server
    {
        int n = listen(_sock, backlog);
        if (n < 0)
        {
            logMessage(Fatal, "Listen failed...");
            exit(LISTEN_ERR);
        }
        logMessage(Debug,"Listen susscess...");

    }

    int Accept(std::string* clientip,uint16_t* clientport) //server -->get a new sock
    {
        struct sockaddr_in client;
        memset(&client,0,sizeof(client));
        socklen_t len = sizeof(client);
        int sock = accept(_sock,(struct sockaddr*)&client,&len);
        *clientip = inet_ntoa(client.sin_addr);
        *clientport = ntohs(client.sin_port);
        // std::cout << "Accept:: " << clientip << *clientip << "-" << *clientport << std::endl; 
        return sock;
    }
    int Fd()
    {
        return _sock;
    }
    int Connect(std::string &serverip, uint16_t serverport) //client
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = ntohs(serverport);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());

        return connect(_sock,(struct sockaddr*)&server,sizeof(server));
    }

    void Close()
    {
        close(_sock);
    }

    ~Sock()
    {
    }

private:
    int _sock;
};